package com.supplychain.scm.core.common.validator.existStringList;

import cn.hutool.core.util.ArrayUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * @author liyichuan
 * @date 2022/06/11
 */
public class ExistListConstraintValidator implements ConstraintValidator<ExistStringList, String> {
    private Set<String> vals = new HashSet<>();
    /**
     * 校验器初始化
     * @param constraintAnnotation
     */
    @Override
    public void initialize(ExistStringList constraintAnnotation) {
        //获取注解的中制定的值
        String[] value = constraintAnnotation.value();
        if(ArrayUtil.isNotEmpty(value)){
            for (String i : value) {
                vals.add(i);
            }
        }

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        // 空不做验证
        if(StringUtils.isBlank(value)){
            return true;
        }
        return vals.contains(value);
    }
}
